<template>
  <van-action-sheet v-model:show="show" title="选择收货地址" closeable @closed="closeDialog">
    <div class="relative">
      <div class="h-50vh bg-[#eee] overflow-y-scroll">
        <div
          class="w-full mb-1rem p-0.5rem rounded text-black bg-white"
          v-for="item in addressList"
          :key="item.id"
        >
          <div class="flex justify-between items-center">
            <div class="flex">
              <span class="mr-0.5rem font-bold">{{ item.contact }}</span>
              <span>{{ item.phone }}</span>
            </div>
            <van-icon
              name="success"
              :color="'#b52d26'"
              v-show="targetId ? targetId === item.id : item.isDefault"
            />
            <van-button
              type="default"
              size="small"
              v-show="!(targetId ? targetId === item.id : item.isDefault)"
              @click="targetId = item.id"
              >使用</van-button
            >
          </div>
          <div class="py-0.5rem border-b">{{ item.address }}</div>
          <div class="my-0.5rem flex justify-between">
            <van-checkbox v-model="item.isDefault" @click="changeDefault(item.id)"
              >默认</van-checkbox
            >
            <div class="flex">
              <div class="mr-0.5rem">
                <van-button type="default" size="small" @click="editAddress(item.id)"
                  >修改</van-button
                >
              </div>
              <van-button type="danger" size="small" @click="delAddress(item.id)">删除</van-button>
            </div>
          </div>
        </div>
      </div>
      <div class="px-0.5rem py-1rem bg-white sticky bottom-0 left-0">
        <div
          class="flex w-full bg-primary border-1px p-0.5rem rounded flex flex-center text-white"
          @click="addAddress"
        >
          + 新增地址
        </div>
      </div>
    </div>
    <van-dialog
      v-model:show="addShow"
      :title="addressData.id ? '修改地址' : '新增地址'"
      show-cancel-button
      :beforeClose="beforeClose"
    >
      <van-form @submit="onSubmit">
        <van-field
          v-model="addressData.contact"
          required
          label="联系人"
          placeholder="请输入联系人"
          :rules="rules.contact"
        />
        <van-field
          v-model="addressData.phone"
          required
          label="电话号码"
          placeholder="请输入电话号码"
          :rules="rules.phone"
        />
        <van-field
          v-model="fieldValue"
          is-link
          readonly
          label="国家"
          placeholder="所属国家"
          @click="showPicker = true"
        />
        <van-popup v-model:show="showPicker" destroy-on-close round position="bottom">
          <van-picker
            v-model="addressData.countryId"
            title="所属国家"
            :columns="countryList"
            @cancel="showPicker = false"
            @confirm="onConfirm"
          />
        </van-popup>

        <van-field
          v-model="addressData.address"
          required
          label="详细地址"
          placeholder="请输入详细地址"
        />

        <van-field name="checkbox" label="默认地址">
          <template #input>
            <van-checkbox v-model="addressData.isDefault">设为默认地址</van-checkbox>
          </template>
        </van-field>
      </van-form>
    </van-dialog>
  </van-action-sheet>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import {
  getAllAddress,
  PostPutOrderAddress,
  PutOrderAddressDefault,
  DeleteAddress,
} from '@/api/member'
import { useConfigStore } from '@/stores/config'

const configStore = useConfigStore()
const router = useRouter()
const show = ref(false)
const addShow = ref(false)
const showPicker = ref(false)
const my_callback = ref()
const fieldValue = ref('')
const targetId = ref()
const addressList = ref([])
const addressData = ref({
  isDefault: false,
})
const countryList = ref([])
const rules = {
  contact: [
    {
      required: true,
      message: '请输入联系人',
      trigger: 'blur',
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入电话号码',
      trigger: 'blur',
    },
  ],
  address: [
    {
      required: true,
      message: '请输入详细地址',
    },
  ],
}

const init = (id, callback) => {
  if (id) targetId.value = id
  configStore.initCountryList().then((res) => {
    if (res && res.length > 0) {
      countryList.value = res.map((item) => {
        return {
          text: item.chineseName,
          value: item.id,
        }
      })
    }
  })
  show.value = true
  if (callback) my_callback.value = callback
  getAddressList()
}

const closeDialog = () => {
  let obj
  if (addressList.value.length === 0) {
    obj = {}
  } else if (targetId.value) {
    obj = addressList.value.find((item) => item.id === targetId.value)
  } else if (addressList.value.find((item) => item.isDefault)) {
    obj = addressList.value.find((item) => item.isDefault)
  } else {
    obj = {}
  }
  my_callback.value && my_callback.value(obj)
  my_callback.value = null
}

const delAddress = (id) => {
  DeleteAddress(id)
  addressList.value = addressList.value.filter((item) => item.id !== id)
  if (targetId.value === id) {
    targetId.value = null
  }
}

// 获取地址列表
const getAddressList = () => {
  getAllAddress().then((res) => {
    if (res.code == 20000 && res.data) {
      addressList.value = [
        ...res.data.map((item) => {
          return {
            ...item,
            isDefault: item.isDefault === '2' ? true : false,
          }
        }),
      ]
    }
  })
}

const editAddress = (id) => {
  const obj = addressList.value.find((item) => item.id === id)
  console.log([obj.countryId])
  addressData.value = {
    ...obj,
  }
  fieldValue.value = countryList.value.find((item) => item.value === obj.countryId)?.text
  addShow.value = true
}

// 修改默认地址
const changeDefault = (id) => {
  if (id) {
    PutOrderAddressDefault(id)
    addressList.value.forEach((item) => {
      if (item.id !== id) {
        item.isDefault = false
      }
    })
  }
}

// 选择国家
const onConfirm = ({ selectedValues, selectedOptions }) => {
  showPicker.value = false
  addressData.contact = selectedValues
  fieldValue.value = selectedOptions[0].text
}

const beforeClose = (action) => {
  if (action === 'confirm')
    return new Promise((resolve) => {
      // action !== 'confirm'  拦截取消操作
      PostPutOrderAddress(addressData.value.id ? 'put' : 'post', {
        ...addressData.value,
        isDefault: addressData.value.isDefault ? '2' : '1',
        countryId: addressData.value.countryId.join(','),
      })
        .then((res) => {
          if (res.code == 20000) {
            if (res.data.isDefault === '2') {
              addressList.value = [
                ...addressList.value.map((item) => {
                  item.isDefault = false
                  return item
                }),
                {
                  ...res.data,
                  isDefault: true,
                },
              ]
            } else {
              addressList.value.push({
                ...res.data,
                isDefault: false,
              })
            }
            addressData.value = {
              isDefault: false,
            }
            resolve(true)
          }
        })
        .catch(() => {
          resolve(false)
        })
    })
  else {
    fieldValue.value = null
    addressData.value = {
      isDefault: false,
    }
    return true
  }
}

const addAddress = () => {
  addShow.value = true
}

defineExpose({
  init,
})
</script>
